<template>
  <el-upload
    ref="CuploadImageOnce"
    :class="[
      'CuploadImageOnce',
      round ? 'CuploadImageOnceRound' :''
    ]"
    :action="action"
    :headers="headers"
    :show-file-list="false"
    :on-success="handleSuccess"
    accept="image/*"
    name="file"
    drag
    :style="{ width: width, height: height }"
  >
    <Cimage v-if="imageUrl || externalImageUrl" :src="imageUrl || externalImageUrl" fit="cover" round width="100%" height="100%" />
    <svg-icon v-else icon-class="uploadImage" class-name="avatar-uploader-icon" />
  </el-upload>
</template>
<script>
import { getToken } from '@/utils/auth'
import {
  fileHandleDeleteImage
} from '@/api/fileHandle'
export default {
  name: 'CuploadImageOnce', // 上传单个图片组件（返回单个文件上传的id）
  props: {
    width: {
      type: String,
      default: '180px'
    },
    height: {
      type: String,
      default: '180px'
    },
    round: { // 是否为圆形
      type: Boolean,
      default: false
    },
    externalImageUrl: { // 默认初始显示的图片地址（如果有传）
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      action: `${process.env.VUE_APP_BASE_API}/fileHandle/qiniuImage`,
      headers: { token: getToken() },
      imageUrl: '' // 上传后生成的url
    }
  },
  methods: {
    // 上传成功
    handleSuccess(res, file, fileList) {
      console.log(res, file, fileList)
      if (res.code === 0) {
        const { data } = res
        // URL.createObjectURL() 静态方法会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL
        this.imageUrl = URL.createObjectURL(file.raw) || data.url // https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
        this.$emit('update:externalImageUrl', data.id)
        this.$message.success('上传成功')
        this.$emit('onSuccess', data.id) // 成功回调
        if (fileList.length > 1) { // 此判断为 已上传一个图片 继续上传把原来的图片覆盖
          // 删除上一个图片
          const filterFileList = fileList.filter(item => item.response.data.id !== data.id) // 获取除了当前上传的图片之外的所的fileList
          const filterIds = filterFileList.map(item => item.response.data.id) // 把id单独集合到数组方便删除
          fileHandleDeleteImage({ ids: filterIds.toString() }).then(res => {
            if (res.code === 0) {
              // 删除后端成功后把本地的也删除
              fileList.forEach((item, index) => {
                filterIds.forEach(it => {
                  if (item.response.data.id === it) {
                    fileList.splice(index, 1)
                  }
                })
              })
            }
          })
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/element-variables.scss";
.CuploadImageOnce{
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  ::v-deep .el-upload{
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    .el-upload-dragger{
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.CuploadImageOnceRound{
  border-radius: 50%;
  ::v-deep .el-upload-dragger{
    border-radius: 50%;
  }
}
::v-deep .el-upload:hover{
  .avatar-uploader-icon{
    color: $--color-primary;
  }
}
.avatar-uploader-icon{
  font-size: 40px;
  color: #8c939d;
}
</style>
